package cn.imatu.framework.tool.core;

import cn.imatu.framework.tool.core.exception.Assert;
import cn.imatu.framework.tool.core.exception.UtilException;

import java.io.IOException;
import java.util.Base64;

/**
 * 图片与base64相互转换
 *
 * @author shenguangyang
 */
public class Base64Utils {

    /**
     * 解码
     *
     * @param base64Str base64字符串
     * @return {@code byte[]}
     * @throws IOException 异常
     */
    public static byte[] decode(String base64Str) throws IOException {
        if (base64Str == null) {
            throw new UtilException("base64Str == null");
        }
        return Base64.getDecoder().decode(base64Str);
    }

    /**
     * 对字节进行编码
     *
     * @param image 图片 {@code byte[]}
     * @return base64
     */
    public static String encode(byte[] image) {
        Assert.notNull(image, "image == null");
        return Base64.getEncoder().encodeToString(image);
    }

    /**
     * @param targetStr 被编码的字符串
     * @return 编码的字符串
     */
    public static String encode(String targetStr) {
        Assert.notNull(targetStr, "targetStr == null");
        return Base64.getEncoder().encodeToString(targetStr.getBytes());
    }
}
